﻿#include "SelectEvent.h"
#include "socketinclude.h"

SelectEvent::SelectEvent()
{

}

SelectEvent::~SelectEvent()
{

}

int SelectEvent::removeFd(const int fd)
{
    for(std::vector<int>::iterator it=fds.begin();it!=fds.end();)
    {
        if(*it == fd)
        {
            it=fds.erase(it);
        }
        else
        {
            ++it;
        }
    }

    return 0;
}
int SelectEvent::addToEvent(const int fd)
{
    std::cout << "----------Add " << fd << " to loop----------" << std::endl;
    fds.push_back(fd);
    return 0;
}

// 调用epoll_wait，并将其交给Event类的handleEvent函数处理
void SelectEvent::Detect(std::vector<MyHandler*> &events)
{
    int max_fd = 0;

    fd_set          rfds;
    struct timeval  to = { 5, 0 };

    FD_ZERO(&rfds);
    for (int i = 0; i < fds.size(); i++)
    {
        FD_SET(fds[i], &rfds);
        if (fds[i] > max_fd)
        {
            max_fd = fds[i];
        }
    }

    int res = select(max_fd + 1, &rfds, NULL, NULL, &to);

    if (res < 0)
    {
        return;
    }
    if (res == 0)
    {
        // do nothing
    }

    if (res > 0)
    {
        printf("server a client......\n");
        for (int i = fds.size()-1; i >=0; --i)
        {
            int _c_socket = fds[i];

            //1. if)
            if (FD_ISSET(_c_socket, &rfds))
            {
                MyHandler *h = new MyHandler(_c_socket);
                events.push_back(h);
            }

        }
    }

}
